import { ref, watch } from 'vue'
import { useUserStore } from '@/stores/user'

// 全局OAuth认证状态
const oauthState = ref('initial') // initial, authenticating, success, failed
const authError = ref(null)

/**
 * OAuth认证状态管理
 */
export const useOAuthState = () => {
	const userStore = useUserStore()

	// 设置认证状态
	const setAuthState = (state, error = null) => {
		oauthState.value = state
		authError.value = error
	}

	// 监听用户登录状态变化
	watch(
		() => userStore.isAuthenticated,
		(isAuthenticated) => {
			if (isAuthenticated && oauthState.value !== 'success') {
				setAuthState('success')
			}
		}
	)

	return {
		oauthState,
		authError,
		setAuthState,
	}
}

/**
 * 页面OAuth状态处理 Hook
 */
export const usePageOAuthHandler = (onAuthSuccess) => {
	const { oauthState, authError } = useOAuthState()
	const userStore = useUserStore()

	// 监听OAuth状态变化
	watch(oauthState, (newState) => {
		if (newState === 'success' && userStore.isAuthenticated) {
			// OAuth登录成功，执行回调
			if (onAuthSuccess && typeof onAuthSuccess === 'function') {
				onAuthSuccess()
			}
		}
	})

	// 检查当前是否已认证
	const isAuthenticated = () => {
		return userStore.isAuthenticated
	}

	// 等待认证完成
	const waitForAuth = () => {
		return new Promise((resolve, reject) => {
			if (userStore.isAuthenticated) {
				resolve(true)
				return
			}

			const unwatch = watch(oauthState, (newState) => {
				if (newState === 'success') {
					unwatch()
					resolve(true)
				} else if (newState === 'failed') {
					unwatch()
					reject(authError.value)
				}
			})

			// 超时处理
			setTimeout(() => {
				unwatch()
				reject(new Error('OAuth认证超时'))
			}, 30000) // 30秒超时
		})
	}

	return {
		oauthState,
		authError,
		isAuthenticated,
		waitForAuth,
	}
}

export default {
	useOAuthState,
	usePageOAuthHandler,
}
